//
//  HuiDanBackVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2021/4/16.
//  Copyright © 2021 吕晶. All rights reserved.
//

#import "HuiDanBackVC.h"
#import "HuiDanBackModel.h"
#import "HuiDanBackCell.h"

@interface HuiDanBackVC ()<UITableViewDelegate,UITableViewDataSource,TZImagePickerControllerDelegate>

@property (nonatomic, strong) HuiDanBackModel *model;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation HuiDanBackVC

-(HuiDanBackModel *)model {
    if (!_model) {
        _model = [HuiDanBackModel new];
        _model.method = 1;
    }
    return _model;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - BottomHeight - NaviHeight)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"回单返回";
    [self.view addSubview:self.tableView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HuiDanBackCell *cell = [HuiDanBackCell HuiDanBackCellWithTableView:tableView];
    cell.model = self.model;
    __weak_self;
    cell.changeBlock = ^(NSInteger idx) {
        if (weakself.model.method != idx) {
            weakself.model.method = idx;
            [tableView reloadData];
        }
    };
    cell.companyBlock = ^(NSString * _Nonnull company) {
        weakself.model.express_company = company;
    };
    cell.numberBlock = ^(NSString * _Nonnull number) {
        weakself.model.express_num = number;
    };
    cell.remarkBlock = ^(NSString * _Nonnull remark) {
        weakself.model.remarks = remark;
    };
    cell.addBlock = ^{
        [weakself chooseImg];
    };
    cell.deleteBlock = ^(NSInteger idx) {
        NSMutableArray *arr = [NSMutableArray arrayWithArray:weakself.model.attachment];
        [arr removeObjectAtIndex:idx];
        weakself.model.attachment = arr;
        [tableView reloadData];
    };
    cell.sureBlock = ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定返回？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself requestForBack];
        }];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        }];
        [alert addAction:sureAction];
        [alert addAction:cancleAction];
        [weakself presentViewController:alert animated:YES completion:nil];
    };
    return cell;
}

- (void)requestForBack {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:self.sta_id forKey:@"sta_id"];
    [dic setObject:@(self.model.method) forKey:@"method"];
    if (self.model.method == 1) {
        //快递
        if (!self.model.express_company.length) {
            [MBProgressHUD leShowFailedHUD:self.view message:@"请输入快递公司"];
            return;
        }else {
            [dic setObject:self.model.express_company forKey:@"express_company"];
        }
        if (!self.model.express_num.length) {
            [MBProgressHUD leShowFailedHUD:self.view message:@"请输入快递单号"];
            return;
        }else {
            [dic setObject:self.model.express_num forKey:@"express_num"];
        }
    }else if (self.model.method == 2) {
        if (!self.model.attachment.count) {
            [MBProgressHUD leShowFailedHUD:self.view message:@"请上传附件"];
            return;
        }else {
            NSMutableString *attachment = [NSMutableString string];
            [self.model.attachment enumerateObjectsUsingBlock:^(HuiDanBackImgModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.path.length) {
                    [attachment appendFormat:@"%@,",obj.path];
                }
            }];
            if (attachment.length) {
                [attachment deleteCharactersInRange:NSMakeRange(attachment.length - 1, 1)];
            }
            if (attachment.length) {
                [dic setObject:attachment forKey:@"attachment"];
            }
        }
    }
    if (self.model.remarks.length) {
        [dic setObject:self.model.remarks forKey:@"remarks"];
    }
    
    [HttpRequest PostWithApi:LogisticsSupplierTaskHuiDanBack params:dic progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            __weak_self;
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"已确认" delayOperation:^{
                [weakself.rt_navigationController popViewControllerAnimated:YES];
            }];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshTaskManagerList object:nil];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HuiDanBackCell *cell = [HuiDanBackCell HuiDanBackCellWithTableView:tableView];
    cell.model = self.model;
    return cell.height;
}

- (void)chooseImg {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:1 delegate:self pushPhotoPickerVc:YES];
        imagePickerVc.allowPickingVideo = NO;
        imagePickerVc.isSelectOriginalPhoto = YES;
        imagePickerVc.allowTakeVideo = NO;   // 在内部显示拍视频按
        imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
        imagePickerVc.showPhotoCannotSelectLayer = YES;
        imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
        [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
            [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }];
        // 你可以通过block或者代理，来得到用户选择的照片.
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            //通过asset获取原图，方法会先返回缩略图，再返回原图
//            [[TZImageManager manager] getOriginalPhotoWithAsset:assets.firstObject newCompletion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
//                if ([info[PHImageResultIsDegradedKey] boolValue]) {
//                    //返回的是缩略图
//                }else {
//                    //返回的是原图
//                    [self requestForUpload:photo];
//                }
//            }];
            [[TZImageManager manager] getOriginalPhotoDataWithAsset:assets.firstObject progressHandler:^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
                
            } completion:^(NSData *data, NSDictionary *info, BOOL isDegraded) {
                [self requestForUpload:data];
            }];
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)requestForUpload:(NSData *)image {
    [MBProgressHUD leShowHUDWithMessage:@"上传中" activity:YES];
    [HttpRequest postImgDataWithUrl:LogisticsSupplierUploadImg_V_1_0 imgData:image imgFile:@"file" withParameter:@{@"type":@(2)} sucess:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            HuiDanBackImgModel *model = [HuiDanBackImgModel new];
            model.url = [responseObject objectForKey:@"url"];
            model.path = [responseObject objectForKey:@"path"];
            NSMutableArray *mut = [NSMutableArray arrayWithArray:self.model.attachment];
            [mut addObject:model];
            self.model.attachment = mut;
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

@end
